import Resume from "../models/resumeModel.js";
import fs from "fs";
import path from "path";

/**
 * 创建新简历控制器
 * @param {Object} req - 请求对象，包含用户信息和简历数据
 * @param {Object} res - 响应对象
 * @returns {Object} 新创建的简历数据
 */
export const createResume = async (req, res) => {
  try {
    const { title } = req.body;
    // 定义简历默认数据结构
    const defaultResumeData = {
      profileInfo: {
        profileImg: null,
        previewUrl: "",
        fullName: "",
        designation: "",
        summary: "",
      },
      contactInfo: {
        email: "",
        phone: "",
        location: "",
        linkedin: "",
        github: "",
        website: "",
      },
      workExperience: [
        {
          company: "",
          role: "",
          startDate: "",
          endDate: "",
          description: "",
        },
      ],
      education: [
        {
          degree: "",
          institution: "",
          startDate: "",
          endDate: "",
        },
      ],
      skills: [
        {
          name: "",
          progress: 0,
        },
      ],
      projects: [
        {
          title: "",
          description: "",
          github: "",
          liveDemo: "",
        },
      ],
      certifications: [
        {
          title: "",
          issuer: "",
          year: "",
        },
      ],
      languages: [
        {
          name: "",
          progress: "",
        },
      ],
      interests: [""],
    };

    // 创建新简历，合并默认数据和请求数据
    const newResume = await Resume.create({
      userId: req.user._id,
      title,
      ...defaultResumeData,
      ...req.body,
    });
    res.status(201).json(newResume);
  } catch (error) {
    res.status(500).json({ message: "创建简历失败", error: error.message });
  }
};

/**
 * 获取当前用户所有简历控制器
 * @param {Object} req - 请求对象，包含用户信息
 * @param {Object} res - 响应对象
 * @returns {Array} 简历列表数组
 */
export const getUserResumes = async (req, res) => {
  try {
    // 查找当前用户的所有简历并按更新时间倒序排列
    const resumes = await Resume.find({ userId: req.user._id }).sort({
      updateAt: -1,
    });
    res.json(resumes);
  } catch (error) {
    res.status(500).json({ message: "获取简历失败", error: error.message });
  }
};

/**
 * 根据ID获取特定简历控制器
 * @param {Object} req - 请求对象，包含简历ID参数和用户信息
 * @param {Object} res - 响应对象
 * @returns {Object} 特定简历数据
 */
export const getResumeById = async (req, res) => {
  try {
    // 查找指定ID且属于当前用户的简历
    const resume = await Resume.findone({
      _id: req.params.id,
      userId: req.user._id,
    });
    // 如果简历不存在返回404错误
    if (!resume) {
      return res.status(404).json({ message: "简历不存在" });
    }
    res.json(resume);
  } catch (error) {
    res.status(500).json({ message: "获取简历失败", error: error.message });
  }
};

/**
 * 更新简历控制器
 * @param {Object} req - 请求对象，包含简历ID参数、用户信息和更新数据
 * @param {Object} res - 响应对象
 * @returns {Object} 更新后的简历数据
 */
export const updateResume = async (req, res) => {
  try {
    // 查找需要更新的简历
    const resume = await Resume.findOne({
      _id: req.params.id,
      userId: req.user._id,
    });
    // 如果简历不存在或无权限访问返回错误
    if (!resume) {
      return res.status(404).json({ message: "简历不存在或未授权" });
    }
    // 使用请求体中的数据更新简历
    Object.assign(resume, req.body);
    const saveResume = await resume.save();
    res.json(saveResume);
  } catch (error) {
    res.status(500).json({ message: "更新简历失败", error: error.message });
  }
};

/**
 * 删除简历控制器
 * @param {Object} req - 请求对象，包含简历ID参数和用户信息
 * @param {Object} res - 响应对象
 * @returns {Object} 删除成功消息
 */
export const deleteResume = async (req, res) => {
  try {
    // 查找要删除的简历
    const resume = await Resume.findOne({
      _id: req.params.id,
      userId: req.user._id,
    });
    // 如果简历不存在或无权限访问返回错误
    if (!resume) {
      return res.status(404).json({ message: "简历不存在或未授权" });
    }
    
    // 删除相关的上传文件
    const uploadsFolder = path.join(process.cwd(), "uploads");
    if (resume.thumbnailLink) {
      const oldThumbnail = path.join(
        uploadsFolder,
        path.basename(resume.thumbnailLink)
      );
      if (fs.existsSync(oldThumbnail)) {
        fs.unlinkSync(oldThumbnail);
      }
    }
    if (resume.profileInfo?.profilePreviewUrl) {
      const oldProfile = path.join(
        uploadsFolder,
        path.basename(resume.profileInfo.profilePreviewUrl)
      );
      if (fs.existsSync(oldProfile)) {
        fs.unlinkSync(oldProfile);
      }
    }
    
    // 从数据库中删除简历记录
    const deleted = await Resume.findOneAndDelete({
      _id: req.params.id,
      userId: req.user._id,
    });
    if (!deleted) {
      return res.status(404).json({ message: "简历不存在或未授权" });
    }
    res.json({ message: "简历已删除" });
  } catch (error) {
    res.status(500).json({ message: "删除简历失败", error: error.message });
  }
};